import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'MyMaterial.dart';

/// 恐龙控件
class IconDragon extends StatefulWidget {
  final bool animate;

  const IconDragon({Key key, this.animate = false}) : super(key: key);

  @override
  _IconDragonState createState() {
    return new _IconDragonState();
  }
}

class _IconDragonState extends State<IconDragon> {
  Timer _timer;
  ///current frame of animation
  int _frame = 0;

  // 只要在父widget中调用setState，子widget的didUpdateWidget就会被调用
  @override
  void didUpdateWidget(IconDragon oldWidget) {
    super.didUpdateWidget(oldWidget);
    _initAnimation();
  }

  @override
  void initState() {
    super.initState();
    _initAnimation();
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return MyMaterial(
      // size: const Size(80, 86),
      widgetSize: const Size(80, 86),
      srcSize: const Size(80, 86),
      srcOffset: _getOffset(_frame),
    );
  }

  void _initAnimation() {
    _timer?.cancel();
    _timer = null;
    if (!widget.animate) {
      return;
    }
    _timer = Timer.periodic(const Duration(milliseconds: 100), (t) {

      if (_frame > 30) {
        _frame = 0;
      }
      setState(() {
        _frame++;
      });
    });
  }

  Offset _getOffset(int frame) {
    int index = 0;
    if (frame < 10) {
      index = frame % 2 == 0 ? 0 : 1;
    } else {
      index = frame % 2 == 0 ? 2 : 3;
    }
    double dx = index * 100.0;
    return Offset(dx, 100);
  }
}
